package com.fanqi.nxplayer.camera;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.hardware.camera2.CameraDevice;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.util.Size;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Toast;

import com.fanqi.nxplayer.R;

public class Camera2Activity extends AppCompatActivity implements Camera2CallBack, ViewTreeObserver.OnGlobalLayoutListener {

    private static final String TAG = Camera2Activity.class.getCanonicalName();
    private static final int ACTION_REQUEST_PERMISSIONS = 1;
    private RoundTextureView previewView;
    private Camera2 camera2;

    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera2);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
        previewView = findViewById(R.id.preview_view);
        previewView.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (camera2 != null) {
            camera2.start();
        }
    }


    private void initCamera() {
        camera2 = new Camera2.Builder()
                .with(this)
                .cameraListener(this)
                .specificCameraId(Camera2.CAMERA_ID_FRONT)
                .previewOn(previewView)
                .previewViewSize(new Point(previewView.getLayoutParams().width, previewView.getLayoutParams().height))
                .rotation(getWindowManager().getDefaultDisplay().getRotation())
                .build();
        camera2.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isAllGranted = true;
        for (int grantResult : grantResults) {
            isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED);
        }
        if (requestCode == ACTION_REQUEST_PERMISSIONS) {
            if (isAllGranted) {
                initCamera();
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    protected boolean checkPermissions(String[] neededPermissions) {
        if (neededPermissions == null || neededPermissions.length == 0) {
            return true;
        }
        boolean allGranted = true;
        for (String neededPermission : neededPermissions) {
            allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;
        }
        return allGranted;
    }

    @Override
    public void onCameraOpened(CameraDevice cameraDevice, String cameraId, Size previewSize, int displayOrientation, boolean isMirror) {
        Log.i(TAG, "onCameraOpened:  previewSize = " + previewSize.getWidth() + "x" + previewSize.getHeight());
    }

    @Override
    public void onPreview(byte[] y, byte[] u, byte[] v, Size previewSize, int yRowStride, int uRowStride, int vRowStride) {
        Log.d(TAG, "onPreview: data");
    }

    @Override
    public void onCameraClosed() {
        Log.d(TAG, "onCameraClosed: ");
    }

    @Override
    public void onCameraError(Exception e) {
        Log.d(TAG, "onCameraError: ");
    }

    @Override
    public void onCaptureData(byte[] byteData) {
        Log.d(TAG, "onCaptureData: ");
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (camera2 != null) {
            camera2.stop();
        }
    }

    @Override
    public void onGlobalLayout() {
        previewView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        ViewGroup.LayoutParams layoutParams = previewView.getLayoutParams();
        int sideLength = Math.min(previewView.getWidth(), previewView.getHeight()) * 3 / 4;
        layoutParams.width = sideLength;
        layoutParams.height = sideLength;
        previewView.setLayoutParams(layoutParams);
        previewView.turnRound();
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        } else {
            initCamera();
        }
    }

    public void capture(View view) {
        camera2.takeCapture();
    }
}
